# 数据降维实战
from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from matplotlib import pyplot as plt
iris = datasets.load_iris()
X, y, target_names = iris.data,iris.target,iris.target_names
titles = ['PCA','LDA']
pca = PCA(n_components=2) # 实例化，定义一个PCA模型，选择前两个主成分
lda = LinearDiscriminantAnalysis(n_components=2) # 实例化，定义一个LDA模型
X_rs = []
X_rs.append(pca.fit(X).transform(X)) # 训练PCA模型，训练结果添加到X_rs中
X_rs.append(lda.fit(X,y).transform(X)) # 训练LDA模型，训练结果添加到X_rs中
print(X_rs)

fig, ax = plt.subplots(1,2,figsize=(9,4))
colors = ["navy","turquoise","darkorange"] # 设置类别颜色
for title, X_r, k in zip(titles,X_rs,[0,1]):
      for color,i,target_name in zip(colors,[0,1,2],target_names):
            ax[k].scatter(X_r[y==i,0],X_r[y==i,1],color=color,alpha=0.8,lw=2,label=target_name)
            ax[k].legend(loc="best",shadow=False,scatterpoints=1)
            ax[k].set_title("%s of IRIS dataset"%title)
plt.show()